from flask import Blueprint, session, redirect, url_for, render_template, request
from sqlalchemy import cast, Integer, func
from sqlalchemy.exc import SQLAlchemyError

from applications.common.utils.response_data import response_success, response_page, response_fail
from applications.models.user_model import User
from applications.models.voice_detail_model import VoiceDetail
from applications.models.voice_package_model import db, VoicePackage

bp = Blueprint('voicePackage', __name__, url_prefix='/voice/package')


@bp.post("/list")
def voicePackageList():
    voicePackage_pageation = db.session.query(
        VoicePackage,
        User,
        VoiceDetail,
    ).join(User, VoicePackage.uid == User.uid) \
        .outerjoin(VoiceDetail, VoicePackage.id == VoiceDetail.package_id) \
        .order_by(VoicePackage.create_time.desc()) \
        .paginate_cus()
    total = voicePackage_pageation.total
    voicePackages = voicePackage_pageation.items
    voice_package_list = []

    for voice_package, user, voice_detail in voicePackages:
        voice_package_data = voice_package.to_dict()
        user_data = user.to_dict() if user else None
        voice_data = voice_detail.to_dict() if voice_detail else None
        voice_package_data['userInfo'] = user_data
        voice_package_data["voiceInfo"] = voice_data
        voice_package_list.append(voice_package_data)

    return response_page(data=voice_package_list,
                         total=total,
                         page=voicePackage_pageation.page,
                         per_page=voicePackage_pageation.per_page,
                         total_pages=voicePackage_pageation.total_pages)


@bp.post("/detail/<int:voicePackage_id>")
def voicePackageDetail(voicePackage_id):
    try:
        # 查询声音包的详细信息，包括用户信息和所有相关的声音详情
        voice_package = VoicePackage.query.get(voicePackage_id)

        if voice_package:
            # 获取声音包的作者信息
            user = User.query.get(voice_package.uid)
            user_data = user.to_dict() if user else None

            # 获取声音包的所有声音详情
            voice_details = VoiceDetail.query.filter_by(package_id=voicePackage_id).all()
            voice_data_list = [voice_detail.to_dict() for voice_detail in voice_details]

            # 构建返回的数据结构
            voice_package_data = voice_package.to_dict()
            voice_package_data['userInfo'] = user_data
            voice_package_data['voiceInfoList'] = voice_data_list

            return response_success(data=voice_package_data)
        else:
            return response_fail(code=404, msg='Voice package not found')

    except Exception as e:
        return response_fail(code=500, msg=str(e))


@bp.get("/recommend")
def recommend_package():
    try:
        # 查询播放量最高的五个语音包
        recommend_voice_packages = db.session.query(VoicePackage) \
            .paginate_cus()

        total = recommend_voice_packages.total
        voicePackages = recommend_voice_packages.items

        recommend_package_list = []

        for voice_package in voicePackages:
            voice_package_data = voice_package.to_dict()

            # 获取声音包的作者信息
            user = User.query.get(voice_package.uid)
            user_data = user.to_dict() if user else None
            voice_package_data['userInfo'] = user_data

            # 获取声音包的所有声音详情
            # voice_details = VoiceDetail.query.filter_by(package_id=voice_package.id).all()
            # voice_data_list = [voice_detail.to_dict() for voice_detail in voice_details]
            # voice_package_data['voiceInfoList'] = voice_data_list

            recommend_package_list.append(voice_package_data)

        return response_page(data=recommend_package_list,
                             total=total,
                             page=recommend_voice_packages.page,
                             per_page=recommend_voice_packages.per_page,
                             total_pages=recommend_voice_packages.total_pages)

    except Exception as e:
        return response_fail(code=500, msg=str(e))


@bp.get("recommendActor")
def recommend_actor():
    try:
        # 查询最新的 5 个用户
        actors = db.session.query(
            User,
            VoiceDetail,
        ) \
            .filter(User.voice_signature_id != 0) \
            .outerjoin(VoiceDetail, VoiceDetail.id == User.voice_signature_id) \
            .limit(5) \
            .all()

        response_data = []
        for user, voice_detail in actors:
            user_data = user.to_dict()
            user_data["voiceInfo"] = voice_detail.to_dict()
            user_data["worksCount"] = voice_detail.to_dict()
            response_data.append(user_data)

        # 返回 JSON 格式的推荐用户数据
        return response_success(data=response_data)

    except Exception as e:
        # 如果有异常，可以返回一个错误响应
        return response_fail(msg=str(e))


@bp.get("topRank")
def topRank():
    top_user = db.session.query(User.avatar,User.username).order_by(User.popular.desc()).first()
    top_voice_package = db.session.query(VoicePackage.avatar, VoicePackage.name).order_by(
        VoicePackage.play_count.desc()).first()
    result = {
        'topUser': {
            'avatar': top_user.avatar,
            'name': top_user.username
        } if top_user else None,
        'topVoicePackage': {
            'avatar': top_voice_package.avatar,
            'name': top_voice_package.name
        } if top_voice_package else None
    }

    return response_success(data=result)


@bp.post("rank")
def rank():
    data = request.json
    # type为1是表示人气排行，，2为作品排行
    type = data["type"]

    if type == 1:
        userList = User.query.order_by(cast(User.popular, Integer).desc()).limit(10).all()
        user_dataList = [user.to_dict() for user in userList]
        return response_success(data=user_dataList)
    elif type == 2:
        voicePackages = db.session.query(VoicePackage, User) \
            .join(User, VoicePackage.uid == User.uid).order_by(VoicePackage.play_count.desc()).limit(10).all()
        voice_package_list = []
        for voice_package, user in voicePackages:
            voice_package_data = voice_package.to_dict()
            user_data = user.to_dict() if user else None
            voice_package_data['userInfo'] = user_data
            voice_package_list.append(voice_package_data)

        return response_success(data=voice_package_list)


@bp.post('/create')
def create_post():
    uid = request.headers.get('uid')
    try:
        data = request.get_json()
        name = data.get('name')
        avatar = data.get('avatar')
        intro = data.get('intro')
        voiceList = data.get('voiceList')
        # 创建并添加 Post 对象
        voicePackage=VoicePackage(uid=uid,name=name,avatar=avatar,intro=intro)
        db.session.add(voicePackage)
        db.session.flush()
        if voiceList:
            for voice_data in voiceList:
                voice_detail = VoiceDetail(package_id=voicePackage.id, voice_url=voice_data["voice_url"], voice_length=voice_data["voice_length"])
                db.session.add(voice_detail)
        else:
            db.session.rollback()
            return response_fail(msg="请上传音频")
        db.session.commit()
        return response_success(msg="创建成功")

    except SQLAlchemyError as e:
        db.session.rollback()
        return response_fail(code=e.code if hasattr(e, 'code') else 500, msg=str(e))

    except Exception as e:
        db.session.rollback()
        return response_fail(code=500, msg=str(e))
